import  axios from "axios";
import qs from 'qs';
import { Message } from 'element-ui';
import router from '../router'
const _api = axios.create({
    baseURL: "",  //url地址
    timeout: 30000,  // 超时时间
    responseType: 'json',    // default
    headers: {
        'Content-Type': 'application/json',
    },
    withCredentials: true,       //允许携带cookie
    validateStatus: status => status === 200,
});

//FormData提交申请时间
const _formApi = axios.create({
    baseURL: "",
    timeout: 30000, // 超时时间
    responseType: 'json', // default
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    // 通过Qs.stringify转换为表单查询参数
    transformRequest: [(data) => {
        data = qs.stringify(data);
        console.log(data)
        return data;
    }],
    withCredentials: true,       //允许携带cookie
    validateStatus: status => status === 200,
});

if(process.env.NODE_ENV == 'development'){
    _formApi.defaults.baseURL = "";
    _api.defaults.baseURL = "";
}
else if(process.env.NODE_ENV == 'production'){
    _formApi.defaults.baseURL = `http://web.sanfengcun.com`;
    _api.defaults.baseURL = `http://web.sanfengcun.com`;
}
console.log(_formApi.defaults.baseURL)
// 错误码统一处理
function defaultReject(info) {
    Message.error(info);
}

// 请求拦截
_api.interceptors.request.use(config=>{
    return config;
});

// 响应拦截
_api.interceptors.response.use(response => {
    let { data } = response;
    let code = data.code;
    if(code === '10001000'){
        return response;
    }
    else{
        return Promise.reject(defaultReject(response.data.message));
    }
});
_formApi.interceptors.request.use(config=>{
    if (localStorage.tsToken) {
        config.headers.token = localStorage.tsToken;
    }
    return config;
},(err) => {
    Promise.reject(err);
});;

// formData响应拦截
_formApi.interceptors.response.use(response => {
    let status = response.data.status;
    if(status == '10001000'){
        return response;
    }
    else if(status == '99999999' || status == '10000000'){
        router.push('/login')   
    }
    else{
        return Promise.reject(defaultReject(response.data.msg));
    }
});

export  {_api,_formApi};